import groovy.sql.Sql

public class Loader extends Pacx {

    def csvdir, queries
    
    Loader() {
        super()
        csvdir = config.doc4.xmltocsv.csvdir
        log = new File(config.doc4.loader.logfile)
        queries = config.doc4.loader.queries
    }

    public static void main(String[] args) {
        def loader = new Loader()
        loader.run()
        loader.sql.close()
    }
    
    def void run() {
        loadPackageFiles()
        try {
            updateDistributionContents()
        } catch (Exception e) {
            println e.getMessage()
            log("*** Error: "+e.getMessage())
        }
        
    }
    
    def void loadPackageFiles() {
        def date = new Date()
        log("== Loading data")
        log("=== CSV folder: $csvdir")
        log("=== Start date: "+date)
        
        try {
    
            log("=== Loading packages...")  
            log("=== Date: "+new Date())
            sql.execute(queries.loadpackages, [csvdir+"/packages.csv"])
    
            log("=== Loading package files...")
            log("=== Date: "+new Date())
            sql.execute(queries.loadfiles, [csvdir+"/package-files.csv"])
    
            log("=== Loading package dependencies...")
            log("=== Date: "+new Date())
            sql.execute(queries.loaddependencies, [csvdir+"/package-dependencies.csv"])
            
        } catch (Exception e) {
            println e.getMessage()
            log("*** Error: "+e.getMessage())
        }
        date = new Date()
        println date
        log("=== End date: "+date)
    }



    def void updateDistributionContents() {
    
        log("=== Updating DISTRIBUTION_PACKAGES...")
        log("=== Date: "+new Date())
        sql.execute(queries.makeold)
        sql.execute(queries.makelatest)
        sql.execute(queries.cleansnapshot)
    
    }

}
